﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using BlueFinity.mvNET.CoreObjects;

namespace fenk.Desarrollo
{
    public partial class ExploradorArchivos : Form
    {
        public ExploradorArchivos()
        {
            InitializeComponent();
            this.cboOpenWith.SelectedIndex = 0;
        }

        private readonly IDictionary<string, string> specialCharactersMapper = new Dictionary<string, string>()
            {  { @"\","%B"},{ "/","%S"},{":","%C"},{"*" , "%A"}, {"?"  ,"%Q"},
            {"<" ,"%L"}, {">","%G"}, {"|", "%V"},{"%","%%"},{".",""}};

        private const string BUFFER_LOCATION = @"C:\Pick\Explorador\{0}\{1}";
        private string _errorMessage = string.Empty;
        private string _user;
        private mvAccount _pickAccount;
        public mvAccount PickAccount
        {
            get { return _pickAccount; }
            set { _pickAccount = value; }
        }
        public string User
        {
            get { return _user; }
            set { _user = value; }
        }

        private void openButton_Click(object sender, EventArgs e)
        {
            if (ValidateRequiredFields())
            {
                GetSaveDataFromPickFile("O");
            }
        }

        private void GetSaveDataFromPickFile(string operationType)
        {
            string itemId = AdaptSpecialCharacters(txtItemId.Text);
            string fileName = AdaptSpecialCharacters(txtPickFileName.Text);

            this.ReadWritePickFile(itemId, fileName, operationType);
        }

        private string AdaptSpecialCharacters(string text)
        {
            foreach (string specialCharacter in specialCharactersMapper.Keys)
            {
                if(text.Contains(specialCharacter))
                {
                   text =  text.Replace(specialCharacter, specialCharactersMapper[specialCharacter]);
                }

            }

            return text;
        }

        private void ReadWritePickFile(string itemId, string fileName, string operationType)
        {
            string programCode = this.OpenBufferFile(fileName, itemId);
            string item = programCode.Replace(DataBASIC.CRLF, DataBASIC.AM);
            _errorMessage = "";
            try
            {
                if (_pickAccount != null)
                {
                    _pickAccount.Login();
                    _pickAccount.CallProg("EXPLORADOR.NET", ref operationType, ref fileName, ref itemId, ref item, ref _user,
                                          ref _errorMessage);
                    _pickAccount.Logout();

                }
            }
            catch (mvException mvEx)
            {
                _pickAccount.Logout();
                _errorMessage = mvEx.Message;
            }
            if (_errorMessage != "")
            {
                MessageBox.Show("Error:\nMensaje de servidor: " + _errorMessage);
            }
            string text = item.Replace(DataBASIC.AM, DataBASIC.CRLF);

            if (operationType.Equals("O"))
            {
                InitializeTextEditorProgram(fileName, itemId, text);
            }
        }
        private string OpenBufferFile(string fileName, string itemId)
        {
            try
            {   
                string filePath = string.Format(BUFFER_LOCATION, fileName, itemId);
                return File.ReadAllText(filePath);
            }
            catch (FileNotFoundException)
            {
                return string.Empty;
            }
        }

        private void InitializeTextEditorProgram(string fileName, string itemId, string text)
        {

            string filePath = string.Format(BUFFER_LOCATION, fileName, itemId);
            File.WriteAllText(filePath, text);

            if (!string.IsNullOrEmpty(this.txtItemId.Text))
                Process.Start(this.cboOpenWith.SelectedItem + ".exe", filePath);

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateRequiredFields())
            {
                GetSaveDataFromPickFile("O");
            }
        }

        private bool ValidateRequiredFields()
        {
            bool isValid = true;
            if (string.IsNullOrEmpty(txtPickFileName.Text))
            {
                MessageBox.Show("Ingrese archivo (full path)", "Leer item");
                txtPickFileName.Focus();
                isValid = false;
            }

            return isValid;
        }
    }
}
